
var LoginScn = cc.Scene.extend({
	onEnter:function(){
		this._super();
		var layer = new LoginMenuLayer();
		layer.init();
		this.addChild(layer);
	}
});

var LoginMenuLayer = cc.Layer.extend({
	init:function(){
		this._super();

		var oldSock = TW.sock;
		this.scheduleOnce(function(){
			if(oldSock){				
				oldSock.disconnect();
			}			
		},2);
		TW = {oldSock:oldSock};
		
		cc.MenuItemFont.setFontName(S_MENU_FONT);
		cc.MenuItemFont.setFontSize(64);
		var tryItem = cc.MenuItemFont.create(S_MENU_TRY, this.tryPlay, this);
		tryItem.setColor(cc.c3b(200,0,0));
		var menu = cc.Menu.create(tryItem);
		this.addChild(menu, 1);
		
		return true;
	},
	
	tryPlay:function(){
		if(cc.COCOS2D_DEBUG==0){
			var thiz = this;
			$.get('http://roughgame.sinaapp.com/svr.php?getSvr', function(data){
				if(typeof data.err =='undefined'){
					thiz.startPlay(data.ip, data.port);
				}
				else{
					Tool.createTip(thiz, S_TIP_SERVERCLOSE);
				}
			}, 'json');
		}
		else{
			this.startPlay('localhost', 16022);
		}
	},
	
	startPlay:function(ip,port){
		if(TW.sock){
			return;
		}
		
		var layer = this;
		TW.sock = io.connect(ip, {port:port, reconnect: false, 'force new connection':true});
		TW.sock.on('connect', function(){
			TW.sock.emit('try');						
		});	
		TW.sock.on('queue', function(time){
			TW.queue_time = time/1000;
			cc.Director.getInstance().replaceScene(new WaitQueueScn());
		});	

		function connectErr(){
			TW.sock.disconnect();
			delete TW.sock;
			Tool.createTip(layer, S_TIP_CONNECTERR);		
		}
		TW.sock.on('disconnect', connectErr);
		TW.sock.on('error', connectErr);
		TW.sock.on('connect_failed', connectErr);
	}
});